package crm.model.teacherPC.connectList;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

import crm.model.Setting;
import crm.model.teacherPC.Manager;
import crm.model.teacherPC.net.StudentPC;


public class ConnectStudent implements Comparable{
	private final String ip;
	private boolean connected;
	private String info;
	StudentPC student;
	boolean reachable;
	int reachCount;

	public ConnectStudent(String ip, String info) {
		this.ip = ip;
		this.info = info;
		connected = false;
		reachCount = 0;

	}
	public ConnectStudent(String ip, String info, boolean connected, StudentPC student) {
		this(ip,info);
		this.connected = connected;
		this.student = student;
	}

	public StudentPC connect(Socket socket, Manager manager){

		student = new StudentPC(socket, manager);
		connected = true;

		return student;
	}
	public StudentPC connect(Manager manager){
		try {
			DatagramSocket udpSocket = new DatagramSocket();

			byte[] buffer = new byte[0];
			DatagramPacket packet = new DatagramPacket(buffer, buffer.length, InetAddress.getByName(ip), Setting.getSendPort());
			udpSocket.send(packet);
			udpSocket.close();

			connect(new ServerSocket(Setting.getTransportPort()).accept(), manager);

		} catch (IOException e) {
			e.printStackTrace();
		}

		return student;
	}
	public StudentPC getStudent() {
		if(connected){
			return student;
		}else {
			throw new NullPointerException("Student ist nicht verbunden");
		}
	}
	public boolean isConnected() {
		return connected;
	}

	public void setConnected(boolean connected, StudentPC student) {
		this.connected = connected;
		this.student = student;
	}

	public String getIP() {
		return ip;
	}
	public String getInfo() {
		return info;
	}
	public void setInfo(String info) {
		this.info = info;
	}

	public int compareTo(Object o) {
		ConnectStudent cs = (ConnectStudent)o;
		if ((cs.connected && this.connected) ||(!cs.connected && !this.connected)){
			return 0;
		}else if (cs.connected && (!this.connected)){
			return -1;
		}else if (!cs.connected && (this.connected)){
			return 1;
		}
		return 0;
	}

	public String toString() {
		return ip;
	}
	public boolean isReachable() {
		if ((reachCount=(++reachCount) % 30 )== 0){
			try {
				if (InetAddress.getByName(ip).isReachable(1000)) {
				   reachable = true;
				   System.out.println("true: " + ip);
				} else {
				    reachable = false;
				    System.out.println("false: " + ip);
				}
			} catch (UnknownHostException e) {
				e.printStackTrace();
				return false;
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}

		}
		System.out.println(reachable + "::" + ip);
		return reachable;
	}
}
